// Challenge Removing Items from Shopping Cart

type CartItem1 = {
  id: number;
  name: string;
  price: number;
};

type ShoppingCart1 = {
  items: CartItem1[];
  addToCart: (item: CartItem1) => void;
  removeFromCart: (id: number) => void;
};

const shoppingCart: ShoppingCart1 = {
  items: [],
  addToCart(item) {
    // TODO: Implement this method
    this.items.push(item);
  },
  removeFromCart(itmeId) {
    // const temporaryArray: CartItem1[] = [];
    // for (const item of this.items) {
    //   if (itmeId !== item.id) {
    //     temporaryArray.push(item);
    //   }
    // }
    // this.items = temporaryArray;

    // this.items.有一个方法entries，可以转为迭代器，或者说数组本身就有这个方法，然后就看一解构
    for (const [key, value] of this.items.entries()) {
      if (value.id === itmeId) {
        console.log(key);
        this.items.splice(key, 1);
        return;
      }
    }
  },
};

console.log(shoppingCart.items);
shoppingCart.addToCart({ id: 1, name: "apple", price: 0.5 });
shoppingCart.addToCart({ id: 2, name: "banana", price: 0.3 });

console.log(shoppingCart.items);

shoppingCart.removeFromCart(1); //移除id为1
console.log(shoppingCart.items);
